import { ref, onMounted } from 'vue';
import axios from 'axios';
import * as pdfjsLib from 'pdfjs-dist';
import { base64ToBytes } from '@/common';
import * as pdfjsWorker from 'pdfjs-dist/legacy/build/pdf.worker.mjs';
import { getPdfFile as getPdfFileStream } from '../../api';

export function usePdfToCanvas() {
  const pdfBufferData = ref('');
  const pdfCanvas = ref();
  let pdfDocumentInstance = null; // 加载pdf文档实例
  const maxRenderPdfNum = ref(1);

  const createLinkDownload = (buffer, filename = '可回溯.pdf') => {
    const blob = new Blob([buffer], { type: 'application/pdf' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = filename;
    link.click();
  };
  // json 下载
  const jsonDownload = async () => {
    const response = await axios.post('/api/download', {});
    console.log('response', response);
    const arrerBuffer = base64ToBytes(response.data.data);
    createLinkDownload(arrerBuffer);
  };
  // blob 下载
  const blobDownload = async () => {
    const response = await axios.get('/api/download', {
      responseType: 'blob',
    });
    console.log('response', response);
    createLinkDownload(response.data);
  };
  /**
   *
   * @param {'json' | 'blob'} type
   */
  const downloadPdf = async (type = 'blob') => (type === 'blob' ? blobDownload() : jsonDownload());

  /**
   * 加载页面
   * @param pdfDocument pdf
   * @param pageNumber 页数
   */
  const renderPdfPage = async (pageNumber) => {
    // 获取页面
    const page = await pdfDocumentInstance.getPage(pageNumber);
    console.log('page', page);

    // 获取设备像素比
    const dpr = window.devicePixelRatio || 1;
    // 实际设备宽度
    const deviceWidth = window.innerWidth || 414;

    // 计算rem基准值（1rem = 100px）
    const remBase = 100;

    // 获取原始viewport以计算合适的缩放比例
    const originalViewport = page.getViewport({ scale: 1.0 });
    // 计算适合屏幕宽度的缩放比例
    const fitScale = (deviceWidth * dpr) / originalViewport.width;
    // 设置更高的基础缩放比例以提高清晰度
    const qualityScale = 2.5;

    // 设置画布尺寸，使用较高的缩放比例来提高清晰度
    const viewport = page.getViewport({ scale: fitScale * qualityScale });
    const canvasEls = pdfCanvas.value[pageNumber - 1];
    const context = canvasEls.getContext('2d', { alpha: false });

    // 设置画布的实际尺寸（考虑设备像素比和质量缩放）
    canvasEls.height = viewport.height;
    canvasEls.width = viewport.width;

    // 设置画布的显示尺寸（使用rem单位）
    canvasEls.style.height = `${viewport.height / (dpr * qualityScale) / remBase}rem`;
    canvasEls.style.width = `${viewport.width / (dpr * qualityScale) / remBase}rem`;

    // 启用图像平滑
    context.imageSmoothingEnabled = true;
    context.imageSmoothingQuality = 'high';

    // 根据设备像素比和质量缩放来调整上下文
    context.scale(1, 1);

    // 渲染页面
    const renderContext = {
      canvasContext: context,
      viewport: viewport,
    };
    await page.render(renderContext).promise;
    if (maxRenderPdfNum.value > pageNumber) {
      renderPdfPage(pageNumber + 1);
    }
  };

  const getPdf = async () => {
    console.log('1111');
    const response = await getPdfFileStream();
    console.log('response', response);
    if (response && response.data?.STATUS === '1') {
      pdfBufferData.value = response.data.data;
    }
  };
  onMounted(async () => {
    new pdfjsLib.GlobalWorkerOptions().workerSrc = pdfjsWorker || {};
    // 发送请求获取pdf
    await getPdf();

    // 将 Blob 数据转换为 ArrayBuffer
    const arrayBuffer = await base64ToBytes(pdfBufferData.value);

    // 将 ArrayBuffer 数据加载到 pdfjs-dist
    const loadingTask = pdfjsLib.getDocument({ data: arrayBuffer });

    pdfDocumentInstance = await loadingTask.promise; // 加载pdf文档

    maxRenderPdfNum.value = pdfDocumentInstance._pdfInfo.numPages; // 存储最大页数
    // 渲染第一页
    renderPdfPage(1);
  });
  return {
    pdfCanvas,
    maxRenderPdfNum,
    downloadPdf,
  };
}
